<template>
  <div class="city-attraction">
    <el-card>
      <!-- 头部 -->
      <template #header>
        <div class="card-header">
          <span>省会城市与景点管理</span>
        </div>
      </template>

      <el-container>
        <!-- 侧边栏 -->
        <el-aside width="300px" class="sidebar">
          <div class="search-section">
            <h3>快速查找</h3>

            <!-- 按名称搜索 -->
            <div class="search-by-name">
              <h4>按名称搜索</h4>
              <el-input
                  v-model="searchKeyword"
                  placeholder="输入景点名或城市名"
                  class="search-input"
                  @keyup.enter="handleSearch"
              >
                <template #append>
                  <el-button @click="handleSearch" :icon="Search" />
                </template>
              </el-input>
            </div>

            <!-- 按平台ID搜索 -->
<!--            <div class="search-by-platform">-->
<!--              <h4>按平台ID搜索</h4>-->
<!--              <el-form :model="platformSearch" label-width="60px" size="small">-->
<!--                <el-form-item label="平台">-->
<!--                  <el-select v-model="platformSearch.platform" placeholder="选择平台">-->
<!--                    <el-option label="携程" value="ctrip" />-->
<!--                    <el-option label="同程" value="tongcheng" />-->
<!--                    <el-option label="马蜂窝" value="mafengwo" />-->
<!--                  </el-select>-->
<!--                </el-form-item>-->
<!--                <el-form-item label="ID">-->
<!--                  <el-input-->
<!--                      v-model="platformSearch.platformId"-->
<!--                      placeholder="输入平台ID"-->
<!--                      @keyup.enter="handlePlatformSearch"-->
<!--                  >-->
<!--                    <template #append>-->
<!--                      <el-button @click="handlePlatformSearch" :icon="Search" />-->
<!--                    </template>-->
<!--                  </el-input>-->
<!--                </el-form-item>-->
<!--              </el-form>-->
<!--            </div>-->

            <div v-if="searchResult" class="search-result">
              <el-alert
                  :title="searchResultText"
                  :type="searchResult.success ? 'success' : 'warning'"
                  show-icon
                  :closable="false"
              />
            </div>
          </div>

          <!-- 添加数据表单 -->
          <div class="add-section">
            <h3>添加新数据</h3>
            <el-tabs v-model="activeTab" type="card">

              <el-tab-pane label="景点/小城市" name="attraction">
                <el-form :model="newAttraction" label-width="80px" size="small">
                  <el-form-item label="名称">
                    <el-input v-model="newAttraction.name" />
                  </el-form-item>
                  <el-form-item label="携程ID">
                    <el-input v-model="newAttraction.ctripId" />
                    <p style="margin-top: 5px">
                      <span style="color: red; ">* </span><span>请参考携程的小城市Id，景点可以为空</span>
                    </p>
                  </el-form-item>
                  <el-form-item label="同程ID">
                    <el-input v-model="newAttraction.tongchengId" />
                    <p style="margin-top: 5px">
                      <span style="color: red; ">* </span><span>请参考同程的小城市Id，景点可以为空</span>
                    </p>
                  </el-form-item>
                  <el-form-item label="马蜂窝ID">
                    <el-input v-model="newAttraction.mafengwoId" />
                    <p style="margin-top: 5px">
                      <span style="color: red; ">* </span><span>请参考马蜂窝的小城市Id，景点可以为空</span>
                    </p>
                  </el-form-item>

                  <el-form-item label="类型">
                    <el-select v-model="newAttraction.type" placeholder="选择类型">
                      <el-option label="景点" value="scenic_spot" />
                      <el-option label="小城市" value="city" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="省会城市">
                    <el-select v-model="newAttraction.provinceCapitalId" placeholder="选择省会城市">
                      <el-option
                          v-for="capital in allCities"
                          :key="capital.id"
                          :label="capital.name"
                          :value="capital.id"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="描述">
                    <el-input v-model="newAttraction.description" type="textarea" />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="addAttraction" size="small">
                      添加景点
                    </el-button>
                  </el-form-item>
                </el-form>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-aside>

        <!-- 主体内容 -->
        <el-main class="main-content">
          <div class="content-header">
            <h2>省会城市列表</h2>
            <el-button @click="loadData" :icon="Refresh" circle />
          </div>

          <div v-loading="loading" class="cities-grid">
            <el-card
                v-for="city in allCities"
                :key="city.id"
                class="city-card"
                shadow="hover"
            >
              <template #header>
                <div class="city-header">
                  <div class="city-info">
                    <span class="city-name">{{ city.name }}</span>
                    <el-tag type="info" size="small">{{ city.province }}</el-tag>
                  </div>
                  <div class="city-actions">
                    <el-button
                        type="primary"
                        :icon="Edit"
                        size="small"
                        @click="openEditCityDialog(city)"
                        circle
                    />
                    <el-button
                        type="danger"
                        :icon="Delete"
                        size="small"
                        @click="confirmDeleteCity(city)"
                        circle
                    />
                  </div>
                </div>
                <!-- 平台ID信息 -->
                <div class="platform-ids">
                  <div class="platform-item" v-if="city.ctripCityId">
                    <el-tag type="success" size="small">携程: {{ city.ctripCityId }}</el-tag>
                  </div>
                  <div class="platform-item" v-if="city.tongchengCityId">
                    <el-tag type="warning" size="small">同程: {{ city.tongchengCityId }}</el-tag>
                  </div>
                  <div class="platform-item" v-if="city.mafengwoCityId">
                    <el-tag type="danger" size="small">马蜂窝: {{ city.mafengwoCityId }}</el-tag>
                  </div>
                </div>
              </template>

              <div class="attractions-section">
                <div class="attractions-header">
                  <h4>相关景点与城市 ({{ city.attractions.length }})</h4>
                  <el-button
                      type="text"
                      size="small"
                      @click="openAddAttractionDialog(city)"
                      :icon="Plus"
                  >
                    添加
                  </el-button>
                </div>

                <div v-if="city.attractions.length === 0" class="no-attractions">
                  暂无相关景点或城市
                </div>
                <div v-else class="attractions-list">
                  <div
                      v-for="attraction in city.attractions"
                      :key="attraction.id"
                      class="attraction-item"
                  >
                    <el-tag
                        :type="attraction.type === 'scenic_spot' ? 'success' : 'warning'"
                        class="attraction-tag"
                        size="small"
                    >
                      <el-icon v-if="attraction.type === 'scenic_spot'">
                        <Location />
                      </el-icon>
                      <el-icon v-else>
                        <House />
                      </el-icon>
                      {{ attraction.name }}
                    </el-tag>

                    <!-- 景点的平台ID -->
                    <div class="attraction-platform-ids">
                      <el-tag v-if="attraction.ctripId" type="success" size="mini">携程: {{ attraction.ctripId }}</el-tag>
                      <el-tag v-if="attraction.tongchengId" type="warning" size="mini">同程: {{ attraction.tongchengId }}</el-tag>
                      <el-tag v-if="attraction.mafengwoId" type="danger" size="mini">马蜂窝: {{ attraction.mafengwoId }}</el-tag>
                    </div>

                    <div class="attraction-actions">
                      <el-button
                          type="primary"
                          :icon="Edit"
                          size="small"
                          @click="openEditAttractionDialog(attraction)"
                          text
                      />
                      <el-button
                          type="danger"
                          :icon="Delete"
                          size="small"
                          @click="confirmDeleteAttraction(attraction)"
                          text
                      />
                    </div>
                  </div>
                </div>
              </div>
            </el-card>
          </div>

          <div v-if="allCities.length === 0 && !loading" class="empty-state">
            <el-empty description="暂无数据" />
          </div>
        </el-main>

        <!-- 省会城市编辑对话框 -->
        <el-dialog
            v-model="cityDialogVisible"
            title="编辑省会城市"
            width="500px"
        >
          <el-form :model="cityForm" label-width="100px" ref="cityFormRef">
            <el-form-item
                label="城市名称"
                prop="name"
                :rules="[{ required: true, message: '请输入城市名称', trigger: 'blur' }]"
            >
              <el-input v-model="cityForm.name" />
            </el-form-item>
            <!-- 平台ID输入 -->
            <el-divider content-position="left">平台ID</el-divider>
            <el-form-item label="携程ID">
              <el-input v-model="cityForm.ctripCityId" placeholder="携程平台城市ID" />
            </el-form-item>
            <el-form-item label="同程ID">
              <el-input v-model="cityForm.tongchengCityId" placeholder="同程平台城市ID" />
            </el-form-item>
            <el-form-item label="马蜂窝ID">
              <el-input v-model="cityForm.mafengwoCityId" placeholder="马蜂窝平台城市ID" />
            </el-form-item>
            <el-form-item
                label="所属省份"
                prop="province"
                :rules="[{ required: true, message: '请输入所属省份', trigger: 'blur' }]"
            >
              <el-input v-model="cityForm.province" />
            </el-form-item>
          </el-form>

          <template #footer>
            <span class="dialog-footer">
              <el-button @click="cityDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="saveCityForm">
                更新
              </el-button>
            </span>
          </template>
        </el-dialog>

        <!-- 景点/小城市编辑对话框 -->
        <el-dialog
            v-model="attractionDialogVisible"
            :title="isEditingAttraction ? '编辑景点/城市' : '添加景点/城市'"
            width="500px"
        >
          <el-form :model="attractionForm" label-width="100px" ref="attractionFormRef">
            <el-form-item
                label="名称"
                prop="name"
                :rules="[{ required: true, message: '请输入名称', trigger: 'blur' }]"
            >
              <el-input v-model="attractionForm.name" />
            </el-form-item>
            <!-- 平台ID输入 -->
            <el-divider content-position="left">平台ID</el-divider>
            <el-form-item label="携程ID">
              <el-input v-model="attractionForm.ctripId" placeholder="请参考携程的小城市Id，景点可以为空" />
            </el-form-item>
            <el-form-item label="同程ID">
              <el-input v-model="attractionForm.tongchengId" placeholder="请参考同程的小城市Id，景点可以为空" />
            </el-form-item>
            <el-form-item label="马蜂窝ID">
              <el-input v-model="attractionForm.mafengwoId" placeholder="请参考马蜂窝的小城市Id，景点可以为空" />
            </el-form-item>
            <el-form-item
                label="类型"
                prop="type"
                :rules="[{ required: true, message: '请选择类型', trigger: 'change' }]"
            >
              <el-select v-model="attractionForm.type" placeholder="选择类型">
                <el-option label="景点" value="scenic_spot" />
                <el-option label="小城市" value="city" />
              </el-select>
            </el-form-item>
            <el-form-item
                label="省会城市"
                prop="provinceCapitalId"
                :rules="[{ required: true, message: '请选择省会城市', trigger: 'change' }]"
            >
              <el-select v-model="attractionForm.provinceCapitalId" placeholder="选择省会城市">
                <el-option
                    v-for="capital in allCities"
                    :key="capital.id"
                    :label="capital.name"
                    :value="capital.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="描述">
              <el-input v-model="attractionForm.description" type="textarea" rows="3" />
            </el-form-item>
          </el-form>

          <template #footer>
            <span class="dialog-footer">
              <el-button @click="attractionDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="saveAttractionForm">
                {{ isEditingAttraction ? '更新' : '添加' }}
              </el-button>
            </span>
          </template>
        </el-dialog>
      </el-container>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {Search, Refresh, Location, House, Edit, Delete, Plus} from '@element-plus/icons-vue'
import citiesApi from '@/api/system' // API模块处理城市数据

// 响应式数据
const loading = ref(false)
const allCities = ref([])
const searchKeyword = ref('')
const searchResult = ref(null)
const searchResultText = ref('')
const activeTab = ref('attraction')

// 对话框控制
const cityDialogVisible = ref(false)
const attractionDialogVisible = ref(false)
const isEditingAttraction = ref(false)

// 表单引用
const cityFormRef = ref(null)
const attractionFormRef = ref(null)

// 表单数据
const cityForm = ref({
  id: null,
  name: '',
  ctripCityId: null,
  tongchengCityId: null,
  mafengwoCityId: null,
  province: ''
})

const attractionForm = ref({
  id: null,
  name: '',
  type: '',
  provinceCapitalId: null,
  ctripId: null,
  tongchengId: null,
  mafengwoId: null,
  description: ''
})

const newAttraction = ref({
  name: '',
  type: '',
  provinceCapitalId: null,
  ctripId: null,
  tongchengId: null,
  mafengwoId: null,
  description: ''
})

// 加载所有城市数据
const loadData = async () => {
  loading.value = true
  try {
    const response = await citiesApi.getAllCities()
    allCities.value = response.data
    ElMessage.success('数据加载成功')
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索功能
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  try {
    const response = await citiesApi.searchCities(searchKeyword.value.trim())

    if (response.data) {
      const capitalId = response.data.id
      const capital = allCities.value.find(city => city.id === capitalId)
      if (capital) {
        searchResult.value = { success: true }
        searchResultText.value = `找到了！"${searchKeyword.value}" 对应的省会城市是：${capital.name}`
      } else {
        searchResult.value = { success: false }
        searchResultText.value = `找到省会城市ID: ${capitalId}，但本地数据中未找到详情`
      }
    } else {
      searchResult.value = { success: false }
      searchResultText.value = `未找到 "${searchKeyword.value}" 对应的省会城市`
    }
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败')
    searchResult.value = { success: false }
    searchResultText.value = '搜索出现错误'
  }
}

// 添加景点/小城市
const addAttraction = async () => {
  if (!newAttraction.value.name || !newAttraction.value.type || !newAttraction.value.provinceCapitalId) {
    ElMessage.warning('请填写完整信息')
    return
  }

  try {
    await citiesApi.addAttraction(newAttraction.value)
    ElMessage.success('景点/城市添加成功')
    // 清空表单
    newAttraction.value = { name: '', type: '', provinceCapitalId: null, description: '' }
    // 重新加载数据
    await loadData()
  } catch (error) {
    console.error('添加景点/城市失败:', error)
    ElMessage.error('添加景点/城市失败')
  }
}

const openEditCityDialog = (city) => {
  cityForm.value = { ...city }
  cityDialogVisible.value = true
}

const saveCityForm = async () => {
  try {
    await cityFormRef.value.validate()

    let axiosResponse = await citiesApi.updateCapitalCity(cityForm.value.id, cityForm.value);
    if (axiosResponse.code === 200) {
      ElMessage.success('省会城市更新成功')
    } else {
      ElMessage.error(axiosResponse.message || '保存省会城市失败')
      return
    }

    cityDialogVisible.value = false
    await loadData()
  } catch (error) {
    console.error('保存省会城市失败:', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.message)
    } else {
      ElMessage.error('保存省会城市失败')
    }
  }
}

const confirmDeleteCity = (city) => {
  ElMessageBox.confirm(
      `确定要删除省会城市 "${city.name}" 吗？如果该城市下有景点或小城市，将无法删除。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      let axiosResponse = await citiesApi.deleteCity(city.id);
      if (axiosResponse.code === 200) {
        ElMessage.success('删除成功')
      } else {
        ElMessage.error(axiosResponse.message || '删除失败')
        return
      }
      await loadData()
    } catch (error) {
      console.error('删除失败:', error)
      if (error.response?.data) {
        ElMessage.error(error.response.message)
      } else {
        ElMessage.error('删除失败')
      }
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 景点/小城市 CRUD 操作
const openAddAttractionDialog = (city) => {
  isEditingAttraction.value = false
  attractionForm.value = {
    id: null,
    name: '',
    type: '',
    provinceCapitalId: city.id,
    ctripCityId: null,
    tongchengCityId: null,
    mafengwoCityId: null,
    description: ''
  }
  attractionDialogVisible.value = true
}

const openEditAttractionDialog = (attraction) => {
  isEditingAttraction.value = true
  attractionForm.value = { ...attraction }
  attractionDialogVisible.value = true
}

const saveAttractionForm = async () => {
  try {
    await attractionFormRef.value.validate()

    if (isEditingAttraction.value) {
      await citiesApi.updateAttraction(attractionForm.value.id, attractionForm.value)
      ElMessage.success('景点/城市更新成功')
    } else {
      await citiesApi.addAttraction(attractionForm.value)
      ElMessage.success('景点/城市添加成功')
    }

    attractionDialogVisible.value = false
    await loadData()
  } catch (error) {
    console.error('保存景点/城市失败:', error)
    ElMessage.error('保存景点/城市失败')
  }
}

const confirmDeleteAttraction = (attraction) => {
  ElMessageBox.confirm(
      `确定要删除 "${attraction.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      await citiesApi.deleteAttraction(attraction.id)
      ElMessage.success('删除成功')
      await loadData()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.city-attraction {

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .header h1 {
    margin: 0;
    font-size: 24px;
    font-weight: 500;
  }

  .sidebar {
    background: #f8f9fa;
    padding: 20px;
    border-right: 1px solid #e9ecef;
    overflow-y: auto;
  }

  .search-section {
    margin-bottom: 30px;
  }

  .search-section h3 {
    margin: 0 0 15px 0;
    color: #333;
    font-size: 16px;
  }

  .search-input {
    margin-bottom: 15px;
  }

  .search-result {
    margin-top: 10px;
  }

  .add-section h3 {
    margin: 0 0 15px 0;
    color: #333;
    font-size: 16px;
  }

  .main-content {
    padding: 20px;
    background: #ffffff;
  }

  .content-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .content-header h2 {
    margin: 0;
    color: #333;
  }

  .cities-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 20px;
  }

  .city-card {
    transition: transform 0.2s ease;
  }

  .city-card:hover {
    transform: translateY(-2px);
  }

  .city-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;
  }

  .city-info {
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .city-name {
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }

  .city-actions {
    display: flex;
    gap: 5px;
  }

  .city-id {
    font-size: 12px;
    color: #666;
  }

  .attractions-section h4 {
    margin: 0 0 10px 0;
    color: #555;
    font-size: 14px;
  }

  .attractions-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }

  .attractions-header h4 {
    margin: 0;
    color: #555;
    font-size: 14px;
  }

  .no-attractions {
    color: #999;
    font-size: 12px;
    font-style: italic;
  }

  .attractions-list {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }

  .attraction-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 4px 0;
  }

  .attraction-tag {
    display: flex;
    align-items: center;
    gap: 4px;
  }

  .attraction-actions {
    display: flex;
    gap: 5px;
    opacity: 0;
    transition: opacity 0.2s;
  }

  .attraction-item:hover .attraction-actions {
    opacity: 1;
  }

  .empty-state {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 200px;
  }

  /* 响应式设计 */
  @media (max-width: 768px) {
    .main-container {
      flex-direction: column;
    }

    .sidebar {
      width: 100% !important;
      height: auto;
    }

    .cities-grid {
      grid-template-columns: 1fr;
    }
  }
}

</style>
